package com.zdp.demo.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zdp.demo.entity.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
public class InjectionMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                // TODO:) 从权限认证上下文中获取
                baseEntity.setCreateBy(1L);
                baseEntity.setCreateTime(LocalDateTime.now());
                baseEntity.setUpdateBy(1L);
                baseEntity.setUpdateTime(LocalDateTime.now());
            }
        } catch (Exception e) {
            throw new RuntimeException("SQL自动注入属性异常 => " + e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                baseEntity.setUpdateBy(1L);
                baseEntity.setUpdateTime(LocalDateTime.now());
            }
        } catch (Exception e) {
            throw new RuntimeException("SQL自动注入属性异常 => " + e.getMessage());
        }

    }
}
